package com.example.qguserconsumer.controller;

import com.example.qgcommon.util.MD5;
import com.example.qgcommon.util.RedisUtil;
import com.example.qgcommon.util.ReturnUtil;
import com.example.qgcommon.util.TokenUtils;
import com.example.qguserconsumer.service.LocalUserService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
//@CrossOrigin
public class UserController {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private LocalUserService service;

    @RequestMapping("/sendSms")
    public Map sendSms(@RequestParam String phone) throws Exception {
         String apiUrl = "https://sms_developer.zhenzikj.com";
         String appId = "105189";
         String appSecret = "NDMwNzAyZDItM2YyYS00NzU2LTg2MDItZmQ3ODE0ZjQ0ZjJh";

        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        //发送短信
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        String result = client.send(phone, "您的验证码为:" + verifyCode + "，该码有效期为5分钟，该码只能使用一次!");

        Map re =  new ObjectMapper().readValue( result,Map.class );

        System.out.println("verifyCode"+verifyCode);

        if ((Integer)(re.get( "code" ))==0){
            //保存手机号和验证码到redis
            //有效果时间为一分钟
            redisUtil.setStr( "code:"+phone,verifyCode,1L);
            return ReturnUtil.success();
        }else{
            return ReturnUtil.fail();
        }

    }

    @RequestMapping("/list")
    public Map list(@RequestParam Map map) throws JsonProcessingException {
        System.out.println("/login++++++++++++++++++++");
        return null;
    }

    @RequestMapping("/codelogin")
    public Map codelogin(@RequestParam Map map) throws JsonProcessingException {

        String phone= (String)map.get( "phone" );

        String code= (String)map.get( "code" );


        if (!redisUtil.exist("code:"+phone)){
            //该号码没有有效的验证码 返回-2
            return ReturnUtil.fail("-2");
        }else{
            String redisCode = redisUtil.getStr( "code:" + phone );
            if (!redisCode.equals( code )){
                //该号码的验证码错误 返回-3
                return ReturnUtil.fail("-3");
            }else{
                //根据系统要求，抢购系统中需要注册后才能短信登录
                //查看该号码的注册用户
                Map user = service.getByPhone(phone);
                if (user==null){
                    //该号码没有注册
                    return ReturnUtil.fail("-4");
                }else {
                    String oldToken = redisUtil.getStr( "user:" + user.get( "id" ) );

                    if (oldToken != null){
                        System.out.println("进来了");
                        //删除之前事情的token
                        redisUtil.del( "token:"+oldToken );
                    }
                    System.out.println(user.get( "id" ));
                    //把用户信息给redis
                    String userJson = new ObjectMapper().writeValueAsString(user);
                    //随机数作为后缀
                    Random random  = new Random();
                    //产生token
                    String token = TokenUtils.createToken( user.get( "id" ) + "", random.nextInt( 10000000 ) + "" );
                    //token 作为key 用户对象作为值
                    redisUtil.setStr("token:"+token,userJson);

                    redisUtil.setStr( "user:"+user.get( "id" ),token);
                    Map resultMap = new HashMap();
                    resultMap.put( "user",user );
                    resultMap.put( "token",token );
                    return ReturnUtil.success(resultMap);
                }
            }
        }

//        //把密码加密
//        String md5password = MD5.getMd5( (String) map.get( "password" ), 10 );
//        //重新设置参数map中的密码为加密的密码
//        map.put( "password" ,md5password);

    }

    @RequestMapping("/login")
    public Map login(@RequestParam Map map) throws JsonProcessingException {

        //把密码加密
        String md5password = MD5.getMd5( (String) map.get( "password" ), 10 );
        //重新设置参数map中的密码为加密的密码
        map.put( "password" ,md5password);
        Map user = service.login(map);
         if (user==null){
             return ReturnUtil.fail();
         }else {
             String oldToken = redisUtil.getStr( "user:" + user.get( "id" ) );

             if (oldToken != null){
                 System.out.println("进来了");
                 //删除事情的token
                 redisUtil.del( "token:"+oldToken );
             }
             System.out.println(user.get( "id" ));
             //把用户信息给redis
             String userJson = new ObjectMapper().writeValueAsString(user);
             //随机数
             Random random  = new Random();
             //产生token
             String token = TokenUtils.createToken( user.get( "id" ) + "", random.nextInt( 10000000 ) + "" );
             //token 作为key 用户对象作为值
             redisUtil.setStr("token:"+token,userJson);

             redisUtil.setStr( "user:"+user.get( "id" ),token);
             Map resultMap = new HashMap();
             resultMap.put( "user",user );
             resultMap.put( "token",token );
             return ReturnUtil.success(resultMap);
         }
    }

    }
